define(function(require, exports, module) {
  var $ = require('$');
  var formcc = require('form');
  var nav = require("bootstrap_nav");
  var bootbox = require("bootbox");
  var dtUtil = require('datatableutil');
  var store = require("store");
  var loader = require("./loader/loader");
  require("bootstrap-datetimepicker.min.css");
  require("bootstrap_commonrequire");
  require("moment");
  require("bootstrap_datetimepicker");
  require('select2.css');
  require('select2');

  exports.init = function(divId, data) {
    // 当前手机号码的id
    var myId = "";
    // 当前checkbox中的内容，即要添加关系的手机号的id和numbers相关信息
    var myCheckboxValue = "";
    // 当前可以用来添加关系的手机号码
    var myNumbers="";
    // 当前用来删除关系的手机号码
    var myNumbersDel="";
    
    // 获取表单数据
    var isvrecord = {};
    if (data)
      isvrecord = data;
    
    
    // 加载表单模板和数据，根据accountId查询的所有号码池信息
    var Table = require("table");
    // 查询内容显示
    new Table({
      attrs : {
        id : "data_table_pool",
        isHovered : false,
        isStriped : true,
        isBordered : false
      },
      // 将该表单数据渲染到accountinfo_data_table3，然后再将其内容放置在data_table_pool中
      renderTo : "accountinfo_data_table3"
    });
    // 数据记录信息显示区
    var isvinfo_data_table = $('#data_table_pool').dataTable( {
      "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
      "bJQueryUI" : false,
      "oLanguage" : {
        "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
      },
      "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
      'bPaginate' : true, // 是否分页
      "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
      "bServerSide" : true, // 指定服务器端分页
      "bDeferRender" : true,// bServerSide,bProcessing,bPaginate均为false
      "bFilter" : true,
      "bSort" : true,
      "bInfo" : true,            // 查询该组织账号下的所有能力号码关系信息 
      "sAjaxSource" : "/numaccrel/queryAllByAccountId.do?accountId=" + isvrecord.id,
      "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT, // 默认分页的每页记录数
      "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
        var queryparam = dtUtil.convert_aoData(aoData);

        // 添加自己的额外参数
        oSettings.jqXHR = $.ajax({
          "dataType" : 'json',
          "contentType" : "application/json;charset=UTF-8",
          "type" : "GET",
          "url" : sSource,
          "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
          "success" : function(json) {
            if (json.flag == '000000') {
              ruleAccount = json;
              dtUtil.successCallback(json, aoData, fnCallback);
              
              // 首先获取#data_table_pool中的内容，放在#div_input_pool_tmp中；
              var div_input_pool_tmp = $("#data_table_pool").parent().html();
              // 然后清除div内容，这样#data_table_pool中的内容为空；
              $("#data_table_pool").parent().empty();
              // 最后在#div_input_pool中显示#div_input_pool_tmp的内容
              $("#div_input_pool").parent().parent().html(div_input_pool_tmp);
              
              $("[name='myDeleteById']:checkbox").on('click', function(){
                if(window.confirm('您确定要执行此操作吗？')){
                  if($(this).attr("checked")=="checked"){
                    
                    // 获取Checkbox中的Value值，包含numbersId和numbers
                    myId=$(this).val();
                    var formdata2= {
                        accountId : isvrecord.id,
                        mynumbersDel : myId
                    };
                    
                    $.ajax({    // 根据组织账号和号码删除能力号码关系表中的一条记录
                      url :"/numaccrel/doDeleteByAccNum.do?mynumbers=" + myId + "&accountId=" + isvrecord.id,
                      dataType : "json",
                      data : "data=" + JSON.stringify(formdata2),
                      type : "POST",
                      async : false,
                      success : function(json) {
                        if(json.flag == '000000'){
                          // 重新加载该界面的内容
                          // 这里重新加载两次页面，因为只加载一次页面的话，data_table_pool并不更新
                          var isvinforeturnform2 = require("./accountinfoformnumaccrel");
                          isvinforeturnform2.init("accountinfo_data_table_edit", isvrecord);
                          var isvinforeturnform2 = require("./accountinfoformnumaccrel");
                          isvinforeturnform2.init("accountinfo_data_table_edit", isvrecord);
                          return true;
                        } else {
                          oauth2Relogin();
                        }
                      },
                      error : function() {
                        loader.noloading();
                        bootbox.alertTimeout("网络请求失败，请重试！");
                      }
                    });
                    return true;
                  }else{
                    return false;
                  }
                }else{
                  return false;
                }
              });
              
            } else {
              oauth2Relogin();
            }
          }
        });
      },

      "aoColumns" : [
      {
        "sTitle" : "id",
        "bSortable" : false,
        "mData" : "id",
        "bVisible" : false,
        "mRender" : function(data, status, full) {
          myId = data;
          return myId;
        }
      }, {
        "sTitle" : "账号",
        "bSortable" : false,
        "mData" : "numbers",
        "mRender" : function(data, type, full) {
          myNumbersDel=data;
          return myNumbersDel;
        }
      }, {
        "sTitle" : "IMS智能多方通话",
        "bSortable" : false,
        "mData" : "talksV2",
        "mRender" : function(data, type, full) {
            if (data == "open")
              return "<div class='fontcir' style='width:110px;font-size:140%'><center>●</center></div>";
            else if (data == "unopen")
              return "<div class='fontcir' style='width:110px;font-size:140%'><center>-</center></div>";
            else
              return "未知";
         }
      }, {
        "sTitle" : "IMS专业会议",
        "bSortable" : false,
        "mData" : "scheduleConference",
        "mRender" : function(data, type, full) {
            if (data == "open")
              return "<div class='fontcir' style='width:85px;font-size:140%'><center>●</center></div>";
            else if (data == "unopen")
              return "<div class='fontcir' style='width:85px;font-size:140%'><center>-</center></div>";
            else
              return "未知";
         }
      }, {
        "sTitle" : "ECP电话会议",
        "bSortable" : false,
        "mData" : "ecpMeet",
        "mRender" : function(data, type, full) {
            if (data == "open")
              return "<div class='fontcir' style='width:85px;font-size:140%'><center>●</center></div>";
            else if (data == "unopen")
              return "<div class='fontcir' style='width:85px;font-size:140%'><center>-</center></div>";
            else
              return "未知";
         }
      }, {
        "sTitle" : "语音通知",
        "bSortable" : false,
        "mData" : "voiceNotice",
        "mRender" : function(data, type, full) {
            if (data == "open")
              return "<div class='fontcir' style='width:60px;font-size:140%'><center>●</center></div>";
            else if (data == "unopen")
              return "<div class='fontcir' style='width:60px;font-size:140%'><center>-</center></div>";
            else
              return "未知";
         }
      }, {
        "sTitle" : "是否占用",
        "bSortable" : false,
        "mData" : "isUse",
        "bVisible" : false,
        "mRender" : function(data, type, full) {
            if (data == "use")
              return "已占用";
            else if (data == "unuse")
              return "未占用";
            else
              return "未知";
         }
      }, {
        "sTitle" : "删除关联关系",
        "bSortable" : false,
        "mData" : "id",
        "mRender" : function(data, type, full) {
          // 以红色的×作为删除按钮，隐藏checkbox控件
          var myDelete = '<label style="width:80px;font-size:140%;color:red;cursor:pointer"><center>×</center>' +
          '<input name="myDeleteById" class="only-checkbox tableCheckbox2" style="display:none;" type="checkbox" value="'+myId+'" /></label>';
          
          return myDelete;
        }
      } ],
      "fnDrawCallback" : function(oSettings) {
        // 表格绘制完成后，去除width属性，使表格可缩放
        $('#' + oSettings.sTableId).css("width", "");
        
      }
    });
    
    
    // 加载表单模板和数据，已启用未占用的数据显示区
    var Table2 = require("table");
    // 查询内容显示
    new Table2({
      attrs : {
        id : "data_table2",
        isHovered : false,
        isStriped : true,
        isBordered : false
      },
      renderTo : "accountinfo_data_table2"
    });
    // 数据记录信息显示区
    var isvinfo_data_table2 = $('#data_table2').dataTable( {
      "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
      "bJQueryUI" : false,
      "oLanguage" : {
        "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
      },
      "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
      'bPaginate' : true, // 是否分页
      "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
      "bServerSide" : true, // 指定服务器端分页
      "bDeferRender" : true,// bServerSide,bProcessing,bPaginate均为false
      "bFilter" : true,
      "bSort" : true,
      "bInfo" : true,  // 查询所有启用的手机号
      "sAjaxSource" : "/numberpool/queryByDataStatus.do",
      "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT, // 默认分页的每页记录数
      "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
        var queryparam = dtUtil.convert_aoData(aoData);

        // 添加自己的额外参数
        oSettings.jqXHR = $.ajax({
          "dataType" : 'json',
          "contentType" : "application/json;charset=UTF-8",
          "type" : "GET",
          "url" : sSource,
          "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
          "success" : function(json) {
            if (json.flag == '000000') {
              ruleAccount = json;
              dtUtil.successCallback(json, aoData, fnCallback);
              
              $("[name='myDataStatus']:checkbox").on('click', function(){ 
                // 获取Checkbox中的Value值，包含numbersId和numbers
                myCheckboxValue=$(this).val();
                // 获取第一个“=”的id，其后面就是numbersId的值
                var myIdRel_tmp_id=myCheckboxValue.indexOf("=");
                // 获取myNumbers的id，其前面就是numbersId的值
                var myIdRel_tmp_id_last=myCheckboxValue.indexOf("myNumbers");
                // 获取最后一个“=”的id，其后面就是numbers的值
                var myNumbers_tmp_id=myCheckboxValue.lastIndexOf ("=");
                // 获取numbersId
                var myIdRel_tmp = myCheckboxValue.substring(myIdRel_tmp_id+1, myIdRel_tmp_id_last);
                // 获取numbers
                var myNumbers_tmp = myCheckboxValue.substring(myNumbers_tmp_id+1, myCheckboxValue.length);
                
                if(window.confirm('您确定要执行此操作吗？')){
                  if($(this).attr("checked")=="checked"){
                    var formdata= {
                        id : isvrecord.id,
                        accountIdentify : isvrecord.identifier,
                        mynumbers : myNumbers_tmp,
                        numberId : myIdRel_tmp
                        // remarks : "Test"
                    };
                    
                    $.ajax({
                      url :"/numaccrel/doEditIsUseByNums.do?mynumbers=" + myNumbers,
                      dataType : "json",
                      data : "data=" + JSON.stringify(formdata),
                      type : "POST",
                      async : false,
                      success : function(json) {
                        if(json.flag == '000000'){
                          // 重新加载该界面的内容
                          // 这里重新加载两次页面，因为只加载一次页面的话，data_table_pool并不更新
                          var isvinforeturnform = require("./accountinfoformnumaccrel");
                          isvinforeturnform.init("accountinfo_data_table_edit", isvrecord);
                          var isvinforeturnform = require("./accountinfoformnumaccrel");
                          isvinforeturnform.init("accountinfo_data_table_edit", isvrecord);
                          return true;
                        } else {
                          oauth2Relogin();
                        }
                      },
                      error : function() {
                        loader.noloading();
                        bootbox.alertTimeout("网络请求失败，请重试！");
                      }
                    });
                    return true;
                  }else{
                    return false;
                  }
                }else{
                  return false;
                }
                
            });
            } else {
              oauth2Relogin();
            }
          }
        });
      },

      "aoColumns" : [
      {
        "sTitle" : "id",
        "bSortable" : false,
        "mData" : "id",
        "bVisible" : false,
        "mRender" : function(data, status, full) {
          myIdRel = data;
          return myIdRel;
        }
      }, {
        "sTitle" : "账号",
        "bSortable" : false,
        "mData" : "numbers",
        "sWidth" : "18%",
        "mRender" : function(data, type, full) {
          myNumbers=data;
          return myNumbers;
        }
      }, {
        "sTitle" : "IMS智能多方通话",
        "bSortable" : false,
        "mData" : "talksV2",
        "sWidth" : "20%",
        "mRender" : function(data, type, full) {
            if (data == "open")
              return "<div class='fontcir' style='width:110px;font-size:140%'><center>●</center></div>";
            else if (data == "unopen")
              return "<div class='fontcir' style='width:110px;font-size:140%'><center>-</center></div>";
            else
              return "未知";
         }
      }, {
        "sTitle" : "IMS专业会议",
        "bSortable" : false,
        "mData" : "scheduleConference",
        "sWidth" : "15%",
        "mRender" : function(data, type, full) {
            if (data == "open")
              return "<div class='fontcir' style='width:85px;font-size:140%'><center>●</center></div>";
            else if (data == "unopen")
              return "<div class='fontcir' style='width:85px;font-size:140%'><center>-</center></div>";
            else
              return "未知";
         }
      }, {
        "sTitle" : "ECP电话会议",
        "bSortable" : false,
        "mData" : "ecpMeet",
        "sWidth" : "15%",
        "mRender" : function(data, type, full) {
            if (data == "open")
              return "<div class='fontcir' style='width:85px;font-size:140%'><center>●</center></div>";
            else if (data == "unopen")
              return "<div class='fontcir' style='width:85px;font-size:140%'><center>-</center></div>";
            else
              return "未知";
         }
      }, {
        "sTitle" : "语音通知",
        "bSortable" : false,
        "mData" : "voiceNotice",
        "sWidth" : "12%",
        "mRender" : function(data, type, full) {
            if (data == "open")
              return "<div class='fontcir' style='width:60px;font-size:140%'><center>●</center></div>";
            else if (data == "unopen")
              return "<div class='fontcir' style='width:60px;font-size:140%'><center>-</center></div>";
            else
              return "未知";
         }
      }, {
        "sTitle" : "能力开启",
        "bSortable" : false,
        "mData" : "dataStatus",
        "bVisible" : false,
        "mRender" : function(data, type, full) {
            if (data == "start")
              return "启用";
            else if (data == "stop")
              return "停用";
            else
              return "未知";
         }
      }, {
        "sTitle" : "建立能力号码关系",
        "bSortable" : false,
        "mData" : "isUse",
        "mRender" : function(data, type, full) {
            if (data == "unuse")
              return '<input name="myDataStatus" class="only-checkbox tableCheckbox" style="width:115px;" type="checkbox" value="myIdRel='+myIdRel+'myNumbers='+myNumbers+'" />';
            else if (data == "use")
              return '<input name="myDataStatus" class="only-checkbox tableCheckbox" style="width:115px;" type="checkbox" value="'+myIdRel+'" checked />';
            else
              return "未知";
         }
      } ],
      "fnDrawCallback" : function(oSettings) {
        // 表格绘制完成后，去除width属性，使表格可缩放
        $('#' + oSettings.sTableId).css("width", "");
      }
    });

    new formcc({
      attrs : {
        title : "能力号码关系编辑",
        spansize : 'span12',
        id : "accountrecordform",
        items : [ {
          isText : true,
          label : "账号",
          id : 'acc_name',
          name : 'acc_name',
          type : "text",
          style : "width:50%",
          readonly : true,
          value : isvrecord.acc_name
        }, {
          isText : true,
          label : "账号标识",
          id : 'identifier',
          name : 'identifier',
          type : "text",
          style : "width:50%",
          readonly : true,
          value : isvrecord.identifier
        }, {
          isText : true,
          label : "本组织账号下的号码池",
          id : 'div_input_pool',
          name : 'div_input_pool',
          type : "text",
          style : "width:50%"
        } ],

        buttons : [ {
          text : "取消",
          id : "btn_cancel",
          style : "btn",
          type : "button",
          icon : "undo",
        } ]

      },
      renderTo : divId,
      afterRender : function() {
        var theme = require('bootstrap_theme');
        theme.setValidateForm($("#accountrecordform"), function() {});

        $('#btn_cancel').on('click', function() {
          // 点击取消时，防止出现#data_table2和data_table_pool中内容为空，所以将其上级内容置空一下
          $("#data_table2").parent().empty();
          $("#data_table_pool").parent().empty();
          $('#accountinfo_data_table_edit').hide();
          $('#accountinfo_data_table').show();
          $('#accountinfo_data_table2').hide();
          $("#accountForm").show();
          $("#queryAreaId").show();
        });

      }
    });
  };

});
